package top.shiyiri.web;

import com.google.gson.Gson;
import top.shiyiri.pojo.User;
import top.shiyiri.service.UserService;
import top.shiyiri.service.impl.UserServiceImpl;
import top.shiyiri.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author Aunean
 * @date 2022/2/1 14:06
 */
public class UserServlet extends BaseServlet {
    private UserService service = new UserServiceImpl();

    /**
     * 处理登录的方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User login = service.login(username, password);
        if (login != null) {
//            resp.sendRedirect("http://localhost:8080/book/pages/user/login_success.jsp");
//            resp.sendRedirect("/book/pages/user/login_success.jsp");
//            resp.sendRedirect("pages/user/login_success.jsp");
            //保存用户登录的信息到Session
            req.getSession().setAttribute("user", login);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        } else {
            //把错误信息，和回显的表单项信息保存到request域中
            req.setAttribute("msg", "用户名或密码错误！");
            req.setAttribute("username", username);
            req.setAttribute("password", password);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        }
    }

    /**
     * 处理注册的方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符编码
        req.setCharacterEncoding("utf-8");

        //获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //String repwd = req.getParameter("repwd");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        //方式一：给JavaBean注入值
        //User user = WebUtils.copyParamsToBean(req, new User());

        Map<String, String[]> parameterMap = req.getParameterMap();
//        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
//            System.out.println(entry.getKey() + "=" + Arrays.asList(entry.getValue()));
//        }
        //方式二：给JavaBean注入值
        User user = WebUtils.copyParamsToBean(parameterMap, new User());
        System.out.println(user);
        //获取Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //检查验证码是否正确
        if (token != null && token.equalsIgnoreCase(code)) {
            //检查用户名是否可用
            if (service.existsUsername(username)) {
                //不可用
                System.out.println("用户名已存在");
                req.setAttribute("msg", "用户名已存在！");
                req.setAttribute("username", username);
                req.setAttribute("email", email);
                req.setAttribute("password", password);
                req.setAttribute("code", code);
                //req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                //可用
                //调用service层保存到数据库
                service.register(user);
//                resp.sendRedirect("http://localhost:8080/book/pages/user/regist_success.jsp");
                resp.sendRedirect("/book/pages/user/regist_success.jsp");
            }
        } else {
            //跳回注册页面
            req.setAttribute("msg", "验证码错误！");
            req.setAttribute("username", username);
            req.setAttribute("email", email);
            req.setAttribute("password", password);
            req.setAttribute("code", code);

            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    /**
     * 用户的注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁Session中用户登录的信息
        req.getSession().invalidate();
        //2.重定向到首页
        resp.sendRedirect(req.getContextPath());
    }

//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String action = req.getParameter("action");
//
//        try {
//            Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            declaredMethod.invoke(this, req, resp);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
////        if ("login".equals(action)) {
////            login(req, resp);//处理登录的需求
////        } else if ("register".equals(action)) {
////            register(req, resp);//处理注册的请求
////        }
//    }
//
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        doPost(req, resp);
//    }


    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数
        String username = req.getParameter("username");
        //调用 service.existsUsername()
        boolean b = service.existsUsername(username);
        //把返回结果封装成为map对象
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername", b);
        Gson gson = new Gson();
        String toJson = gson.toJson(resultMap);
        //通过响应的字符输出流返回
        resp.getWriter().write(toJson);
    }
}
